using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using HyperLocal.Core;
using HyperLocal.Service;

namespace HyperLocal.MVC.Controllers
{
    public class EventController : Controller
    {
        //
        #region Controller Logic
        // GET: /Events/
        [Authorize]
        public ActionResult Index()
        {
            Repository repo = ConnectionService.getRepository;

            return View(repo.Find<LocalOrbEvent>(x => x.Active));
        }

        //
        // GET: /Events/Details/5
        [Authorize]
        public ActionResult Details(Guid id)
        {
            Repository repo = ConnectionService.getRepository;
            return View(repo.First<LocalOrbEvent>(x => x.LocalOrbEventId == id));
        }

        //
        // GET: /Events/Create

        public ActionResult Create()
        {
            setCreateFrom(); return View();
        }

        //
        // POST: /Events/Create
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {

            if (!isValid(collection))
            {
                setCreateFrom(); 
                return View();
            }

            Repository repo = ConnectionService.getRepository;
            try
            {
                var currentUser = repo.First<LocalOrbUser>(x => x.UserName.ToUpper() == User.Identity.Name.ToUpper());
                currentUser.LocalOrbEvents.Add(new LocalOrbEvent()
                {
                    LocalOrbEventId = Guid.NewGuid(),
                    LocalOrbCommunity = currentUser.LocalOrbCommunity,
                    EventTitle = collection["EventTitle"],
                    EventDescription = collection["EventDescription"],
                    CostOfEvent = Convert.ToDecimal(collection["CostOfEvent"]),
                    DateOfEvent = Convert.ToDateTime(collection["DateOfEvent"]),
                    TimeOfEvent = DateTime.Parse(collection["TimeOfEvent"]).TimeOfDay,
                    DateCreated = DateTime.Now,
                    LocalOrbEventTypeId = Convert.ToInt32(collection["EventTypeId"]),
                    Active = true,
                    Deleted = false
                });

                repo.Update<LocalOrbUser>(currentUser);

                return RedirectToAction("Index", "Profile");
            }
            catch (Exception e)
            {
                setCreateFrom();
                ModelState.AddModelError("_FORM", e.StackTrace);
                return View();
            }
        }

        //
        // GET: /Events/Edit/5
        [Authorize]
        public ActionResult Edit(Guid id)
        {
            Repository repo = ConnectionService.getRepository;
            return View(repo.First<LocalOrbEvent>(x => x.LocalOrbEventId == id));
        }

        //
        // POST: /Events/Edit/5
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            Repository repo = ConnectionService.getRepository;
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View(repo.First<LocalOrbEvent>(x => x.LocalOrbEventId == id));
            }
        } 

        #endregion

        #region Main Logic


        private void setCreateFrom()
        {
            Repository repo = ConnectionService.getRepository;
            ViewData.Add("EventTypeId", new SelectList(repo.All<LocalOrbCommunityType>(), "LocalOrbCommunityTypeId", "TypeName"));
            ViewData.Add("TimeOfEvent", new SelectList(getTimes(), "TimeValue", "Time"));
            ViewData.Add("CostOfEvent", new SelectList(getCosts(), "CostValue", "Cost"));
        }

        private IList<timeHelper> getTimes()
        {
            IList<timeHelper> retList = new List<timeHelper>();

            retList.Add(new timeHelper("1:00 AM", "1:00 AM"));
            retList.Add(new timeHelper("2:00 AM", "2:00 AM"));
            retList.Add(new timeHelper("3:00 AM", "3:00 AM"));
            retList.Add(new timeHelper("4:00 AM", "4:00 AM"));
            retList.Add(new timeHelper("5:00 AM", "5:00 AM"));
            retList.Add(new timeHelper("6:00 AM", "6:00 AM"));
            retList.Add(new timeHelper("7:00 AM", "7:00 AM"));

            //Add the rest here

            return retList;
        }

        private IList<costHelper> getCosts()
        {
            IList<costHelper> retList = new List<costHelper>();

            retList.Add(new costHelper("0.00", "$0.00"));
            retList.Add(new costHelper("10.00", "$10.00"));


            //Add the rest here

            return retList;
        }

        #endregion

        #region Form Validation


        /// <summary>
        /// Validates the Collection contains all of the require
        /// Information
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        private bool isValid(FormCollection collection)
        {
            bool valid = true;

            if (string.IsNullOrEmpty(collection["EventTitle"]))
            {
                ModelState.AddModelError("_FORM", "Event Title Missing");
                valid = false;
            }

            if (string.IsNullOrEmpty(collection["EventDescription"]))
            {
                ModelState.AddModelError("_FORM", "Event Description Missing");
                valid = false;
            }

            if (string.IsNullOrEmpty(collection["CostOfEvent"]))
            {
                ModelState.AddModelError("_FORM", "Cost Of Event Missing");
                valid = false;
            }
            if (string.IsNullOrEmpty(collection["DateOfEvent"]))
            {
                ModelState.AddModelError("_FORM", "Date Of Event Missing");
                valid = false;
            }
            if (string.IsNullOrEmpty(collection["TimeOfEvent"]))
            {
                ModelState.AddModelError("_FORM", "Time Of Event Missing");
                valid = false;
            }
            if (string.IsNullOrEmpty(collection["EventTypeId"]))
            {
                ModelState.AddModelError("_FORM", "Event Type Id Missing");
                valid = false;
            }

            return valid;
        }

        #endregion
    }

    public class timeHelper
    {          
        public string TimeValue { get; set; }
        public string Time { get; set; }
        public timeHelper(string timeValue, string time)
        {
            TimeValue = timeValue;
            Time = time;
        }
    }

    public class costHelper
    {
        public string CostValue { get; set; }
        public string Cost { get; set; }
        public costHelper(string costValue, string cost)
        {
            CostValue = costValue;
            Cost = cost;
        }
    }
}
